<?php

namespace app\api\controller\center;

use app\common\controller\ApiController;
use app\service\JwtService;
use think\facade\Request;
use think\facade\Cache;
use app\api\model\User;
use think\exception\ValidateException;

// 登录相关操作
class Auth
{
     
    /**
     * 用户登录
     * @param Request $request
     * @return \think\response\Json
     */
    public function login(Request $request)
    {
        $username = Request::post('username');
        $passwords = Request::post('passwords');
        $type = Request::post('type', 1); // 登录类型

        // 验证用户名密码
        $user = User::where('username', $username)->find();

        if (!$user || !password_verify($passwords, $user->passwords)) {
            return json(['code' => 401, 'message' => '用户名或密码错误']);
        }
        
        if ($user->status != 1) {
            return json(['code' => 403, 'message' => '账号已被禁用']);
        }
        
        // 生成Token
        $token = JwtService::generateToken($user->toArray(), $type);

        // 更新用户登录信息
        $user->last_login_time = date('Y-m-d H:i:s');
        $user->last_login_ip = $_SERVER['REMOTE_ADDR'];
        $user->save();
        
        // 返回Token和用户基本信息
        return json([
            'code' => 200,
            'message' => '登录成功',
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $user->id,
                    'username' => $user->username,
                    'email' => $user->email,
                    'avatar' => $user->avatar
                ]
            ]
        ]);
    }
    

    /**
     * 退出登录
     * @param Request $request
     * @return \think\response\Json
     */
    public function logout(Request $request)
    {
        $token =Request::header('Authorization');

        if ($token) {
            // 将Token加入黑名单
            $this->addTokenToBlacklist($token);
        }
        
        return json(['code' => 200, 'message' => '退出成功']);
    }
    
    /**
     * 刷新Token
     * @param Request $request
     * @return \think\response\Json
     */
    public function refreshToken(Request $request)
    {
        $token = $request->header('Authorization');
        if (!$token) {
            return json(['code' => 401, 'message' => 'Token不能为空']);
        }
        
        try {
            $newToken = JwtService::refreshToken($token);
            return json([
                'code' => 200,
                'message' => '刷新成功',
                'data' => ['token' => $newToken]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 401, 'message' => $e->getMessage()]);
        }
    }
    
    /**
     * 将Token加入黑名单
     * @param string $token
     */
    private function addTokenToBlacklist(string $token)
    {
        try {
            $data = JwtService::verifyToken($token);
            $expireTime = $data['exp'] - time();
            if ($expireTime > 0) {
                // 使用Redis存储黑名单Token
                Cache::store('file')->set('jwt:blacklist:' . $token, 1, $expireTime);
            }
        } catch (\Exception $e) {
            // Token无效则不处理
        }
    }
    
    /**
     * 检查Token是否在黑名单中
     * @param string $token
     * @return bool
     */
    public static function isTokenInBlacklist(string $token): bool
    {
        return Cache::store('file')->has('jwt:blacklist:' . $token);
    }

}